C Program for Fibonacci Numbers | Using for loop, while loop & recursion
The Fibonacci series is a sequence where the next term is obtained by the sum of previous two terms.
Fibonacci series- 0, 1, 1, 2, 3, 5, 8, 13, 21,....etc. The first two numbers of Fibonacci series are 0 and 1.
C Program to display Fibonacci series:
Using for loop
#include<stdio.h>
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements: ");
scanf("%d",&number);
printf("\n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}
Using while loop
#include <stdio.h>
int main() {
int t1 = 0, t2 = 1, nextTerm = 0, n,i=2;
printf("Enter the number of elements: ");
scanf("%d", &n);
// displays the first two terms which is always 0 and 1
printf("Fibonacci Series: %d %d ", t1, t2);
nextTerm = t1 + t2;
while (i < n)
{
printf("%d ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
i++;
}
return 0;
}
Using recursion
#include<stdio.h>
void printFibonacci(int n)
{
static int n1=0,n2=1,n3;
if(n>0)
{
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
printFibonacci(n-1);
}
}
int main(){
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
printFibonacci(n-2);//n-2 because 2 numbers are already printed
return 0;
}
Output
Enter the number of elements: 5
Fibonacci Series: 0 1 1 2 3
Enter the number of elements: 9
Fibonacci Series: 0 1 1 2 3 5 8 13 21
No comments: